import { injectable } from "inversify";
import passport from "passport";
import jsonwebtoken from "jsonwebtoken";
import { ExtractJwt, Strategy } from 'passport-jwt'


@injectable()
export class JWT {
  private secret = 'xiaopeng'

  private jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: this.secret
  }
  
  constructor () {
    this.strategy()
  }

  strategy () {
    let str = new Strategy(this.jwtOptions, (jwtPayload, done) => {
      done(null, jwtPayload)
    })
    passport.use(str)
  }

  static middleware () {
    
    return passport.authenticate('jwt', { session: false })
  }

  // 生成token
  public createToken (data: object) {
    return jsonwebtoken.sign(data, this.secret, {
      expiresIn: '1h'
    })
  }

  // 关联express
  public init () {
    return passport.initialize()
  }
}